const express = require('express');
const mqtt = require('mqtt');
const cors = require('cors');
const WebSocket = require('ws');
const bodyParser = require('body-parser');
const mysql = require('mysql2/promise');
const path = require('path');

const app = express();
const PORT = 3002;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../client-vue/dist')));

// 使用内存存储日志
const logs = [];

// MySQL 连接池 - SSH隧道模式
let mysqlPool = null;
async function initMySQL() {
  try {
    const {
      // 云服务器直连模式
      MYSQL_HOST = '8.149.243.80',  // 云服务器公网IP
      MYSQL_PORT = '3307',
      MYSQL_USER = 'root',
      MYSQL_PASSWORD = '123456',
      MYSQL_DATABASE = 'mqtt_app'
    } = process.env;

    mysqlPool = mysql.createPool({
      host: MYSQL_HOST,
      port: Number(MYSQL_PORT),
      user: MYSQL_USER,
      password: MYSQL_PASSWORD,
      database: MYSQL_DATABASE,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0
    });

    // 初始化表
    await mysqlPool.query(`CREATE TABLE IF NOT EXISTS logs (
      id BIGINT PRIMARY KEY AUTO_INCREMENT,
      timestamp VARCHAR(32) NOT NULL,
      type VARCHAR(32) NOT NULL,
      topic VARCHAR(255) DEFAULT NULL,
      message MEDIUMTEXT,
      qos TINYINT DEFAULT 0,
      retained TINYINT DEFAULT 0,
      source VARCHAR(32) DEFAULT NULL,
      client_id VARCHAR(128) NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      INDEX idx_ts (timestamp),
      INDEX idx_type (type),
      INDEX idx_topic (topic),
      INDEX idx_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`);

    console.log('MySQL 云服务器连接成功，日志表就绪');
  } catch (err) {
    console.warn('MySQL 云服务器连接失败，继续使用内存日志:', err.message);
    mysqlPool = null;
  }
}

// ... 其余代码与server.js相同 ...
